package com.corner.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;

import com.corner.app.GlobalParams;
import com.corner.utils.imageloader.MemoryCache;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * Bitmap工具
 * Created by Administrator on 2015/5/2.
 */
public class BitmapUtil {
    public static int getExifOrientation(String filepath) {
        int degree = 0;
        ExifInterface exif = null;

        try {
            exif = new ExifInterface(filepath);
        } catch (IOException ex) {
            // MmsLog.e(ISMS_TAG, "getExifOrientation():", ex);
        }

        if (exif != null) {
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            if (orientation != -1) {
                // We only recognize a subset of orientation tag values.
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;
                    default:
                        break;
                }
            }
        }

        return degree;
    }

    /**
     * 获得圆角图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedBitmap(Bitmap bitmap) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG |
                    Paint.FILTER_BITMAP_FLAG));
            Paint paint = new Paint();
            paint.setFlags(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(0xff424242);
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            RectF rectF = new RectF(rect);
            canvas.drawRoundRect(rectF, bitmap.getWidth() / 2.0f, bitmap.getHeight() / 2.0f, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
            MemoryCache.getInstance().clear();
        }
        return null;
    }

    /**
     * 获得圆角图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedBitmap(Bitmap bitmap, Rect srcRect, Rect desRect, int xRaids, int yRaids) {
        try {
            Bitmap output = Bitmap.createBitmap(desRect.width(), desRect.height(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG |
                    Paint.FILTER_BITMAP_FLAG));
            Paint paint = new Paint();
            paint.setFlags(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(0xff424242);
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            canvas.drawRoundRect(new RectF(desRect), xRaids, yRaids, paint);
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, srcRect, desRect, paint);
            return output;
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
            MemoryCache.getInstance().clear();
        }
        return null;
    }

    public static void compressBitmap(String srcPath, String desPath) throws IOException {
        try {
            Bitmap bitmap = getBitmap(srcPath);
            int quality = 80;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
//            int MaxLength = 0;
////            if(baos.toByteArray().length/1024<1000){
////                MaxLength = 350;
////            }else {
////                MaxLength = 500;
////            }
//            MaxLength = 1024;
//            while (baos.toByteArray().length / 1024 > MaxLength) {
//                baos.reset();
//                quality -= 10;
//                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
//            }
            FileUtil.write2SDCard(new File(desPath), baos.toByteArray());
            bitmap.recycle();
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
            MemoryCache.getInstance().clear();
            compressBitmap(srcPath, desPath);
        }
    }

    /**
     * 已经做好旋转的图片
     * @param srcPath
     * @return
     */
    private static Bitmap getBitmap(String srcPath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcPath, options);
        int width = options.outWidth;
        int height = options.outHeight;
        int widScale = width / (GlobalParams.screenWidth);
        int heiScale = height / (GlobalParams.screenHeight);
        int scale = widScale > heiScale ? widScale : heiScale;
        if (scale < 1) {
            scale = 1;
        }
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        int orientation = getExifOrientation(srcPath);

        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);
        Bitmap newBitmap;
        if(orientation == 90 || orientation == 180 || orientation == 270){
            //Roate preview icon according to exif orientation
            Matrix matrix = new Matrix();
            matrix.postRotate(orientation);
            newBitmap = Bitmap.createBitmap(
                    bitmap,
                    0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
        }else{
            //do not need roate the icon,default
            newBitmap = bitmap;
        }
        return newBitmap;
    }

    public static Bitmap cutBitmap(Bitmap bitmap, float[] scale) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Paint paint = new Paint();
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(0xff424242);
        paint.setAntiAlias(true);
        Rect rect = new Rect((int) (scale[0] * width), (int) (scale[1] * height), (int) (scale[2] * width), (int) (scale[3] * height));
        Bitmap output = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawBitmap(bitmap, rect, new Rect(0, 0, output.getWidth(), output.getHeight()), paint);
        return output;
    }

    public static void cutBitmap(String srcPath, String desPath, float[] scale) throws IOException {
        Bitmap bitmap = getBitmap(srcPath);
        Bitmap cutBitmap = cutBitmap(bitmap, scale);
        bitmap.recycle();
        int quality = 80;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cutBitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        FileUtil.write2SDCard(new File(desPath), baos.toByteArray());
        cutBitmap.recycle();
    }
}
